package org.confucianismframework.orm.sql.produce.support;

import org.confucianismframework.orm.enums.SQLType;
import org.confucianismframework.orm.pattern.EntityNamePattern;
import org.confucianismframework.orm.annotation.RegisterSQLStrategy;
import org.confucianismframework.orm.sql.produce.SqlProduce;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * 生成 Insert 语句
 *
 * @author zy
 */
@RegisterSQLStrategy(SQLType.INSERT)
public class InsertSqlProduce implements SqlProduce {

    @Override
    public String produce(Object instance) {

        Class<?> instanceClazz = instance.getClass();

        List<Field> fields = Arrays.asList(instanceClazz.getDeclaredFields());

        StringBuilder sql = new StringBuilder(100);

        // insert into table_name(
        sql.append("INSERT INTO " + EntityNamePattern.humpToLine(instanceClazz.getSimpleName()));
        sql.append("(");

        // insert into table_name(column1, column2,
        for (Field field : fields) {

            field.setAccessible(true);

            String column = field.getName();

            // beanName -> bean_name
            sql.append(EntityNamePattern.humpToLine(column)).append(",");

        }

        // insert into table_name(column1, column2) VALUES (
        sql = sql.deleteCharAt(sql.length() - 1);
        sql.append(") VALUES (");

        // insert into table_name(column1, column2) VALUES (val_1, val_2
        for (Field field : fields) {
            sql.append("?,");
        }

        // insert into table_name(column1, column2) VALUES (val_1, val_2)
        sql = sql.deleteCharAt(sql.length() - 1);
        sql.append(")");

        return sql.toString();
    }
}
